#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class UdpServer
{
public:
    UdpServer(uint16_t port, const std::string& ip = "")
        : _ip(ip)
        , _port(port)
        , _sockfd(-1)
    {

    }

    ~UdpServer()
    {

    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            //创建套接字失败
            std::cerr << "create socket error, errno: " << errno << " strerrno : " << strerror(errno) << std::endl;
            exit(1); 
        }

        //bind,绑定ip和端口号
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        int n = bind(_sockfd, (struct sockaddr*)&addr, sizeof(addr));
        if (n < 0)
        {
            //bind失败
            std::cerr << "bind ip and port error, errno: " << errno << " strerrno : " << strerror(errno) << std::endl;
            exit(2);
        }
    }

    //启动服务器
    void Start()
    {
        char buffer[1024];
        std::string str;
        struct sockaddr_in addr;
        socklen_t addrlen = sizeof(addr);
    
        while (true)
        {
            //收到用户端发来的命令，并执行
            std::string res;
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &addrlen);
            if (n > 0)
            {
                buffer[n] = 0;
                if (strstr(buffer, "rm") != nullptr)
                {
                    std::cout << "you don't have enough permissions" << std::endl;
                    res += "you can't do it\n";

                    sendto(_sockfd, res.c_str(), res.size(), 0, (struct sockaddr*)&addr, sizeof(addr));
                    continue;
                }

                FILE* fp = popen(buffer, "r");
                if (fp == nullptr)
                {
                    std::cout << "读取命令失败 " << std::endl;
                    res += "read command fail";
                } 
                else 
                {
                    char temp[1024];
                    while(fgets(temp, sizeof(temp), fp) > 0)
                    {
                        res += temp;
                    }
                }
                pclose(fp);

                //将文件写回
                sendto(_sockfd, res.c_str(), res.size(), 0, (struct sockaddr*)&addr, sizeof(addr));
            }
        }
    }

private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};